<?php
/**
 * Description of ValidatorDeUsuario
 *
 * @author Mariano
 */
class ValidatorDeUsuario extends sfValidatorBase
{
    public function  configure($options = array(), $messages = array()) {
        //parent::configure($options, $messages);
        $this->addOption('username_field','username');
        $this->addOption('password_field','password');
        $this->addOption('throw_global_error',false);

        $this->setMessage('invalid', 'El usuario o password no es correcto');

        
    }
    protected function  doClean($value) {
        $username = isset($value[$this->getOption('username_field')] ) ? $value[$this->getOptions('username_field')] : '' ;
        $password = isset($value[$this->getOption('password_field')] ) ? $value[$this->getOptions('password_field')] : '' ;

        $allowEmail = sfConfig::get('app_sf_guard_plugin_allow_login_with_email', true);
        $method = $allowEmail ? 'retrieveByUsernameOrEmailAddress' : 'retrieveByUsername';

      // don't allow to sign in with an empty username
         if ($username)
         {
          $user = $this->getTable()->retrieveByUsername($username);
            // user exists?
           if($user)
           {
            // password is ok?
            if ($user->getIsActive() && $user->checkPassword($password))
            {
            return array_merge($values, array('user' => $user));
            }
            }
         }
        if ($this->getOption('throw_global_error'))
        {
      throw new sfValidatorError($this, 'invalid');
        }

    throw new sfValidatorErrorSchema($this, array(
        $this->getOption('username_field') => new sfValidatorError($this,'invalid')
        ));

    
    }
    protected function getTable()
    {
        return Doctrine::getTable('Usuario');
    }
}
?>
